//
//  ChatViewController.swift
//  EyeVisionForDoctors
//
//  Created by PMC on 2020/2/7.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit

let kKeyboardChangeFrameTime: TimeInterval = 0.25

class ChatViewController: BaseViewController {
    
    
    var businessType: Int  = 1
    
    var status :chatStatusEnum?
    
    let diagnoseId: String
    
    let cloudOutpatientStatus: OrderStatus
    let readyFlag: Int
    
    init(with diagnoseId: String, outpatientStatus: OrderStatus = .all, readyFlag: Int = 0) {
        self.diagnoseId = diagnoseId
        self.cloudOutpatientStatus = outpatientStatus
        self.readyFlag = readyFlag
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loadData()
        
        setupUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setupKeyboardManager(enable: false)
        setupNotification()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        setupKeyboardManager(enable: true)
        removeNotification()
        UserDefaults.removeDoctorPic()
        if let playing = RecordManager.sharedInstance.player?.isPlaying, playing {
            RecordManager.sharedInstance.stopPlay()
        }
        UIDevice.current.isProximityMonitoringEnabled = false
    }
    
    var handlerClosure: (() -> Void)?
    
    lazy var chatBarView: ChatBarView = {
        let barView = ChatBarView()
        barView.isHidden = true
        barView.delegate = self
        barView.inputTextView.delegate = self
        barView.speakView.recordView.delegate = self
        return barView
    }()
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style: .plain)
        tableView.isHidden = true
        tableView.showsHorizontalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.tableFooterView = UIView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .background
        tableView.register(YSGAdvistoryUnstartCell.nibForCell(),
                           forCellReuseIdentifier: YSGAdvistoryUnstartCell.reuseIdentifier())
        tableView.register(YSGAdvisoryStartAndEndCell.nibForCell(),
                           forCellReuseIdentifier: YSGAdvisoryStartAndEndCell.reuseIdentifier())
        tableView.register(ChatTextCell.self, forCellReuseIdentifier: ChatTextCell.reuseIdentifier())
        tableView.register(ChatImageCell.self, forCellReuseIdentifier: ChatImageCell.reuseIdentifier())
        tableView.register(ChatPrescriptionCell.nibForCell(),
                           forCellReuseIdentifier: ChatPrescriptionCell.reuseIdentifier())
        tableView.register(ChatRecordCell.self, forCellReuseIdentifier: ChatRecordCell.reuseIdentifier())
        return tableView
    }()
    
    lazy var endLabel: UILabel = {
        let label = UILabel()
        label.isHidden = true
        label.font = .regular(16)
        label.textAlignment = .center
        label.textColor = .textLight
        label.text = "问诊已结束，不能再咨询"
        return label
    }()
    
    lazy var detailView: ChatAdvisoruDetailView = {
        let view = UINib.loadViewFrom(ChatAdvisoruDetailView.self)
        view.isHidden = true
        return view
    }()
    
    lazy var titleView = UINib.loadViewFrom(ChatTitleView.self)
    
    lazy var timerView = UINib.loadViewFrom(YSGChatTimerView.self)
    
    /// chat bar view 的 bottom Constraint
    var chatBarViewPaddingBottomConstranit: Constraint?
    
    var viewModel: ChatViewModel? {
        didSet {
            tableView.isHidden = false
        }
    }
    
    var detailVM: AdvisoryDetailViewModel? {
        didSet {
            guard let vm = detailVM else { return }
            title = vm.chatReceiveName + (businessType  == 2 ? "(复诊)" : "(咨询)")
            
            detailView.isHidden = false
            detailView.configure(with: vm)
            timerView.configure(with: vm.remainingTime,status: status ?? .advisory)
            
            switch vm.diagType {
            case .advisory,.nurseAdvisory:
                chatBarView.isHidden = vm.status != .diagnosing
                if vm.status != .diagnosing {
                    tableView.contentInset = UIEdgeInsets.zero
                }
                endLabel.isHidden = vm.status != .endDiagnosed && vm.status != .rejected
                timerView.isHidden = vm.status != .diagnosing
                
                switch vm.status {
                case .notDiagnosed:
                    insertUnstartCell(vm)
                case .diagnosing:
                    insertStartCell(vm)
                default:
                    insertStartCell(vm)
                    insertEndCell(vm)
                }
            case .cloud:
                timerView.isHidden = true
                switch cloudOutpatientStatus {
                case .notStart:
                    chatBarView.isHidden = readyFlag != 1
                    endLabel.isHidden = readyFlag == 1
                    endLabel.text = "云门诊未报道，暂不能咨询"
                case .processing, .waitFinished:
                    chatBarView.isHidden = false
                    endLabel.isHidden = true
                default:
                    chatBarView.isHidden = true
                    endLabel.isHidden = false
                }
            case .unknow:
                timerView.isHidden = true
                chatBarView.isHidden = true
                endLabel.isHidden = true

            }
        
            
            tableView.reloadData()
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) {
                self.tableView.scrollBottomToLastRow()
            }
        }
    }
    
    var current: Int = 1
    
    var waitSendMsgs = [ChatMsgModel]()
}

// MARK: - Setting
extension ChatViewController {
    private func setupUI() {
        detailView.imageClickedClosure = { (imageUrls, index) in
            let brows = JSImagBrows(parentController: self,
                                    images: imageUrls,
                                    andCurrentIndex: index,
                                    andPlaceHolderImage: nil)
            brows?.modalPresentationStyle = .fullScreen
            brows?.show()
        }
        
        timerView.isHidden = true
        view.addSubview(tableView)
        view.addSubview(chatBarView)
        view.addSubview(timerView)
        view.addSubview(endLabel)
        view.addSubview(detailView)
        setupUILayout()
        
        tableView.mj_header = refreshHeader(action: #selector(loadLastMsg))
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(chatBarViewEndEditing))
        tap.cancelsTouchesInView = false
        tableView.addGestureRecognizer(tap)
        
        view.bringSubviewToFront(detailView)
        view.bringSubviewToFront(chatBarView)
    }
    
    func setupUILayout() {
        detailView.frame = CGRect(x: 0, y: navBarH, width: screenW, height: detailVM?.viewHeight() ?? 0)
        
        timerView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(chatBarView.snp.top)
            make.height.equalTo(30)
        }
        
        chatBarView.snp.makeConstraints { [weak self] (make) in
            guard let strongSelf = self else { return }
            make.left.right.width.equalToSuperview()
            strongSelf.chatBarViewPaddingBottomConstranit = make.bottom.equalToSuperview().offset(-bottomSafeH).constraint
            make.height.equalTo(kChatBarViewOriginalHeight)
        }
        
        endLabel.snp.makeConstraints { (make) in
            make.top.equalTo(chatBarView)
            make.left.right.equalToSuperview()
            make.height.equalTo(30)
        }
        
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 30, right: 0)
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(detailView.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(chatBarView.snp.top)
        }
    }
    
    func setupKeyboardManager(enable: Bool) {
        IQKeyboardManager.shared.enable = enable
    }
}

// MARK: - Event
extension ChatViewController {
    @objc private func chatBarViewEndEditing() {
        view.endEditing(true)
    }
}
